package cn.itsource.ymcc.mq.listener;

import cn.itsource.ymcc.domain.CourseOrder;

import cn.itsource.ymcc.dto.Order2PayParamDto;
import cn.itsource.ymcc.service.ICourseOrderService;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

//@Component  下面的注解是组合注解，可以不加
@RocketMQTransactionListener(txProducerGroup="TxOrder2PayGroup")//事务监听器组名
@Slf4j
public class Order2PayTransMsgListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService courseOrderService;
    //执行本地事务

    /**
     * 保存订单
     * 保存子订单
     *
     * @param message 消息体（保存支付单的内容）
     * @param arg 订单和子订单参数
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        log.info("执行本地事务");
        if(arg == null){//没有参数执行本地事务，直接回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        CourseOrder courseOrder = (CourseOrder) arg;
        try {
            //执行本地订单保存
            courseOrderService.saveOrderAndItems(courseOrder);
            log.info("消费者完成消费");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    //检查本地事务
    /**
     * 根据订单号检查本地订单是否已经保存成功
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] body = (byte[]) message.getPayload();
            String jsonStr = new String(body, StandardCharsets.UTF_8);
            Order2PayParamDto order2PayParamDto = JSONObject.parseObject(jsonStr, Order2PayParamDto.class);
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(order2PayParamDto.getOrderNo());
            if(courseOrder != null){
                log.info("消费者完成消费");
                return RocketMQLocalTransactionState.COMMIT;//检查本地事务成功
            }
            return RocketMQLocalTransactionState.ROLLBACK;//检查本地事务执行失败
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
